import 'package:flutter/material.dart';
import 'package:flutter_nest_life/pages/profile/index.dart';
import 'package:flutter_nest_life/utils/TokenManager.dart'; // 确保导入
import 'pages/404.dart';
import 'pages/house/house_list.dart';
import 'pages/login/index.dart';
import 'pages/notice/index.dart';
import 'pages/tabs_page.dart';

void main() {
  runApp(MaterialApp(
    routes: {
      '/': (context) => const TabsPage(),
      '/notice_detail': (context) => const NoticeDetail(),
      '/login': (context) => const LoginPage(),
      // '/profile': (context) => const ProfilePage(),
    },
    // 默认启动页面
    initialRoute: '/',
    // 路由拦截 - pushNamed 进行跳转时 && 访问的页面路径并不是上方routes中所定义
    onGenerateRoute: (setting) {
      final token = tokenManager.getToken();
      if (token.isEmpty) {
        return MaterialPageRoute(builder: (context) => const LoginPage());
      } else if (setting.name == '/profile') {
        final args = setting.arguments as Map<String, dynamic>? ?? {}; // 空值处理
        return MaterialPageRoute(
            builder: (context) => ProfilePage(
                  userInfo: args['userInfo'] ?? {}, // 添加空值回退
                ));
      } else if (setting.name == '/house') {
        return MaterialPageRoute(builder: (context) => const HouseList());
      }
      // 如果路由不存在，则返回404页面
      return MaterialPageRoute(builder: (context) => const NotFound());
    },
  ));
}
